package student.collection.list;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

/**
    Collections.synchronizedCollection
 */
public class ArrayListTest2 {

    public static void main(String[] args) {

        Collection<Object> arrayList = Collections.synchronizedCollection(new ArrayList<>());

        new Thread(() -> {
            for (int i = 1; i <= 1000; i++) {
                arrayList.add(i + "");
            }
        }, Thread.currentThread().getName()).start();

        new Thread(() -> {
            for (int i = 1001; i < 2000; i++) {
                arrayList.add(i + "");
            }
        }, Thread.currentThread().getName()).start();

        // 打印所有结果
        System.out.println("元素总共：" + arrayList.size() + "个");
        // 迭代器是非线程安全的
        synchronized (arrayList) {
            Iterator<Object> iterator = arrayList.iterator();
            while (iterator.hasNext()) {
                System.out.println("元素为：" + iterator.next());
            }
        }
    }
}
